package bakaserver.qqchat;

import org.bukkit.ChatColor;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;

import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.AsyncPlayerChatEvent;

public final class qqchat extends JavaPlugin implements Listener {
	public Logger consoleLogger = getLogger();
	public String QQ, Password, EnableGroup, EnableQQ;
	public String SToGamePerfix, SToGroupPerfix, SToQQPerfix,
			ToGameBroadcastPerfix;
	public String VerifyCode;
	public File cfg;
	public YamlConfiguration yamlConfig;
	public boolean debug;
	public WebQQ conn;
	public void disableSelf(){
		this.setEnabled(false);
	}
	void DebugLogger(String m) {
		if (debug)
			consoleLogger.info(m);
	}
	public void broadcastMessage(String source,String qq, String msg){
		String msg2=ToGameBroadcastPerfix;
		msg2 = ChatColor.stripColor(msg2.replace("$source", source)
				.replace("$qq", qq)
				.replace("$msg", msg));
		for(Player p: getServer().getOnlinePlayers()) p.sendMessage(msg2);
	}
	void OutputExcpetion(String from, Exception e) {
		getLogger().info("-> In " + from);
		getLogger().info("->" + e.getMessage());
		getLogger().info("->" + e.toString());
		getLogger().info("->" + e.getLocalizedMessage());
	}

	boolean CreateConfig() {
		try {
			InputStream in = getResource("config.yml");
			OutputStream out = new FileOutputStream(cfg);

			byte[] buffer = new byte[1024];
			int len;
			while ((len = in.read(buffer)) != -1) {
				out.write(buffer, 0, len);
			}

			in.close();
			out.close();
		} catch (Exception e) {
			consoleLogger.info("Can't create config.yml file.");
			return false;
		}
		return true;
	}

	boolean LoadConfig() {
		yamlConfig = new YamlConfiguration();
		try {
			yamlConfig.load(cfg);
			QQ = yamlConfig.getString("QQ.QQ");
			Password = yamlConfig.getString("QQ.Password");
			EnableGroup = yamlConfig.getString("QQ.EnableGroup");
			EnableQQ = yamlConfig.getString("QQ.EnableQQ");

			SToGamePerfix = yamlConfig.getString("ChatPerfix.SToGamePerfix");
			SToGroupPerfix = yamlConfig.getString("ChatPerfix.SToGroupPerfix");
			SToQQPerfix = yamlConfig.getString("ChatPerfix.SToQQPerfix");
			ToGameBroadcastPerfix = yamlConfig
					.getString("ChatPerfix.ToGameBroadcastPerfix");

			debug = yamlConfig.getBoolean("Debug");

		} catch (FileNotFoundException e) {
			consoleLogger.info("Config file not found , plugin disabled");
			setEnabled(false);
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			consoleLogger
					.info("IO Exception catched , please check your harddisk");
			return false;
		} catch (InvalidConfigurationException e) {
			e.printStackTrace();
			consoleLogger
					.info("Config invalid! Check your config and reload plugin");
			return false;
		}
		return true;
	}

	boolean Reload(CommandSender sender) {
		if (!sender.hasPermission("bqc.reload")) {
			sender.sendMessage("权限不足");
			consoleLogger.info("Player " + sender.getName()
					+ "tried reload plugin!");
			return false;
		} else {
			
			LoadConfig();
			consoleLogger.info("Reload successful.");
			return true;
		}
	}
 
	@Override
	public void onEnable() {
		if (!getDataFolder().exists()) {
			consoleLogger
					.info("Can't load config file ,please config the plugin after use it.");
			getDataFolder().mkdir();
			CreateConfig();
		}
		cfg = new File(getDataFolder(), "config.yml");
		if (!cfg.exists()) {
			CreateConfig();
			consoleLogger.info("Config loaded fail, copy form jar.");
			setEnabled(false);
		}
		if (cfg.exists())
			LoadConfig();
		//init mini qq
		conn = new WebQQ(Integer.parseInt(QQ), Password ,this);
		try {
			conn.getPoolThread().join();
		} catch (Exception e) {
			consoleLogger.info("Error while create MiniQQClient , recheck your account info");
			this.setEnabled(false);
		}
		getServer().getPluginManager().registerEvents(this, this);
		consoleLogger.info("BAKAServer Level System Started Successfuly!!");
	}

	@Override
	public void onDisable() {
		consoleLogger.info("BAKAServer Level System Closed Successfully!");
	}

	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String label,
			String[] args) {
		DebugLogger("On commands");
		switch (cmd.getName().toLowerCase()){
		case "qcreload":
			return Reload(sender);
		default:
			return false;
		}
	}
 
	@EventHandler
	public void onPlayerChat(AsyncPlayerChatEvent event) {
		if(event.getMessage().charAt(0) == this.SToGroupPerfix.charAt(0) )
			conn.sendMsgToGroup(Integer.parseInt(this.EnableGroup), 
					event.getPlayer().getName() + ":" + event.getMessage());
		DebugLogger("Player Chat");
	}

}
